﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TagTokenMultiSelectBox.xaml.cs" company="GT">
//   Gunther Taborga
// </copyright>
// <summary>
//   Interaction logic for TagTokenMultiSelectBox.xaml
// </summary>
// --------------------------------------------------------------------------------------------------------------------

// TODO refactored=true
namespace BatchID3.Editor.Controls
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Windows.Controls;

    using BatchID3.Enumerations;

    public partial class TagTokenMultiSelectBox : UserControl
    {
        private readonly ListBoxItemsMover listBoxItemsMover;

        public TagTokenMultiSelectBox()
        {
            this.InitializeComponent();

            this.listBoxItemsMover = new ListBoxItemsMover(this.listBox);

            this.SetupListBox();
        }

        public ListBox ListBox
        {
            get
            {
                return this.listBox;
            }
        }

        public IEnumerable<TagToken> SelectedTagTokens
        {
            get
            {
                if (this.listBox.SelectedItems.Count == 0)
                {
                    return Enumerable.Empty<TagToken>();
                }

                var selectedItems = this.listBox.SelectedItems.OfType<TagToken>();
                return this.TagTokens.Where(selectedItems.Contains).ToList();
            }
        }

        private Button UpButton
        {
            get
            {
                return this.upButton;
            }
        }

        private Button DownButton
        {
            get
            {
                return this.downButton;
            }
        }

        private ObservableCollection<TagToken> TagTokens { get; set; }

        public void SetTagTokens(IEnumerable<TagToken> tagTokens)
        {
            this.TagTokens = new ObservableCollection<TagToken>(tagTokens);
            this.ListBox.ItemsSource = this.TagTokens;
        }

        public void SetupSelectedTokens(IEnumerable<TagToken> preSelectedTagTokens)
        {
            var tagTokens = this.listBox.Items.Cast<TagToken>().Where(preSelectedTagTokens.Contains);

            foreach (var item in tagTokens)
            {
                this.listBox.SelectedItems.Add(item);
            }
        }

        private void SetupListBox()
        {
            this.UpButton.Click += (sender, args) => this.listBoxItemsMover.MoveUp(this.TagTokens);
            this.DownButton.Click += (sender, args) => this.listBoxItemsMover.MoveDown(this.TagTokens);
        }
    }
}